package com.service;

import org.springframework.stereotype.Service;

import java.util.*;

@Service

public class ChatRoomService {
    private final Map<String, Set<String>> chatRooms = new HashMap<>();
    public List<String> joinRoom(String roomId, String userId) {
        chatRooms.putIfAbsent(roomId, new HashSet<>());
        Set<String> users = chatRooms.get(roomId);
        users.add(userId);
        return getOtherUsers(roomId, userId);
    }

    public List<String> leaveRoom(String roomId, String userId) {
        Set<String> users = chatRooms.get(roomId);
        if (users != null) {
            users.remove(userId);
            if (users.isEmpty()) {
                chatRooms.remove(roomId);
            }
        }
        return getOtherUsers(roomId, userId);
    }
    private List<String> getOtherUsers(String roomId, String userId) {
        Set<String> users = chatRooms.getOrDefault(roomId, Collections.emptySet());
        List<String> otherUsers = new ArrayList<>(users);
        otherUsers.remove(userId);
        return otherUsers;
    }
}
